// 云函数入口文件
const cloud = require('wx-server-sdk')
const moment = require('moment')

cloud.init()


const db = cloud.database();
const collectTable = db.collection('oil_prices');
const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  // 逻辑：找出当前符合加油站ID的，根据时间排序，取最新一条，如果存在就更新对应所有标号油价，没有的取全局油价。如果没有数据，直接对这个加油站插入新的一条价格.
  // oil_prices 所有燃料标号的数据


  //查出最新一条数据
  let rows = await db.collection('oil_prices').where({
    station_id: event.stationId,
  }).orderBy('created_time', 'desc').get();
  let oldData = rows.data[0]
  if(oldData){//存在历史价格
    let oilPrices = oldData.oils; //取出历史油价
    let oil_id = oldData._id;
    for (let item of oilPrices) {
      if (item.oil_type == event.oilType) { //更新对应标号燃油的价格
        item.price = event.price
      }
    }
    if (moment(oldData.created_time).format('YYYY-MM-DD') === moment(db.serverDate()).format('YYYY-MM-DD')){ //当日存在新价格
      //进行更新
      let updateRes = await db.collection('oil_prices').doc(oil_id).update({
        data: {
          oils: oilPrices
        }
      });

      if (updateRes){
        return {
          code: 200,
          msg: '油价更新成功',
          data: updateRes
        }
      }
    }else{
      db.collection('oil_prices').add({
        data: {
          auditing: true,
          created_time: db.serverDate(),
          oils: oilPrices,
          station_id: event.stationId,
        }
      })

    }

  }else{ //直接添加新价格
    db.collection('oil_prices').add({
      data: {
        auditing: true,
        created_time: db.serverDate(),
        oils: [{
          oil_type: event.oilType,
          price:event.price
        }],
        station_id: event.stationId,
      }
    })

  }


}